package code;

/**
 * @author xiaovcloud
 * @description:
 * @since 2021/8/23 12:52
 */
public class SynchronizedTest {
	public static void main(String[] args) {

	}

	/**
	 * 用在普通方法
	 */
	private synchronized void synchronizedMethod() throws InterruptedException {
		System.out.println("同步普通方法");
		Thread.sleep(2000);
	}

	/**
	 * 用在静态方法
	 */
	private synchronized static void synchronizedStaticMethod() throws InterruptedException {
		System.out.println("同步静态方法");
		Thread.sleep(2000);
	}

	/**
	 * 用在类
	 */
	private void synchronizedClass() {
		synchronized (SynchronizedTest.class) {
			System.out.println("synchronizedClass");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 用在类
	 */
	private void synchronizedGetClass() {
		synchronized (this.getClass()) {
			System.out.println("synchronizedGetClass");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 用在this
	 */
	private void synchronizedThis() {
		synchronized (this) {
			System.out.println("同步this实例");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private SynchronizedTest LOCK = new SynchronizedTest();

	/**
	 * 用在对象
	 */
	private void synchronizedInstance() {
		synchronized (LOCK) {
			System.out.println("同步对象实例");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
